var express = require('express');
var con = require('dao/dbConnect');
var sqlUntil = require('../util/sqlUntil');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('user/user_info_list');
});

router.get('/toUpdate', function(req, res, next) {
  res.render('user/user_info');
});

router.get('/group', function(req, res, next) {
  client = con.connect();
  user = req.session.user;
  client.query("select ug.group_id groupId,g.group_name groupName from base_user_group ug, base_group_info g where ug.group_id = g.id and ug.user_id = '"+user.id+"' and ug.status = '1'",
    function(err, results, fields){
      res.render('user/group',{groups:results});
  });
});

router.get('/toAddGroup', function(req, res, next) {
  res.render('user/group_add');
});

router.get('/addGroup', function(req, res, next) {
  client = con.connect();
  //插入爱好组详情表
  client.query("insert into base_group_info(group_name) values(?)",
    [req.query.groupName],
    function(err, results, fields){
      var groupId = results.insertId;
      //插入用户-爱好组表
      user = req.session.user;
      client.query("insert into base_user_group(user_id, group_id) values(?,?)",
        [user.id, groupId],
        function(err, results, fields){
          //插入爱好组详情
          var itemArr = req.query.groupItem.split(";");
          var insertItem = "insert into base_group_item(group_id, item_name) values(?, ?),(?, ?)";
          var cols = ['group_id', 'item_name'];
          var objs = [];
          for(i in itemArr){
            var obj = [groupId,itemArr[i]]
            objs.push(obj);
          }
          sqlUntil.insertOjbs('base_group_item', cols, objs);
          res.send('ok');

        });
  });
});

router.get('/delGroup', function(req, res, next) {
    var groupId = req.query.groupId;
    var userId = user = req.session.user.id;
    client = con.connect();
    client.query("update base_user_group set status = '2' where user_id = ? and group_id = ?",[userId, groupId],
    function(err, results, fields){
      res.send('ok');
    });
});

module.exports = router;
